#!/bin/bash
ROOT_PATH=$(pwd)

# GitLab地址和项目名称列表
GITLAB_URL="http://192.168.100.1/demo/"
COMMON_NAME="my"
PROJECTS=("app" "bpp" "cpp")
BRANCH_NAME_SUFFIX="1.2" # 分支名称的后缀

# 克隆并切换到指定分支函数
clone_and_checkout_branch() {
    local module_name=${COMMON_NAME}-"$1.git" # 添加.git后缀
    local branch_name="${COMMON_NAME}-$2-$BRANCH_NAME_SUFFIX" # 生成分支名称
    local clone_dir="$3"

    local formatted_module_name=$(basename "$module_name" ".git") # 提取项目名称

    echo "Checking if $clone_dir/$formatted_module_name exists..."
    if [ -d "$clone_dir/$formatted_module_name" ]; then
        echo "Directory $clone_dir/$formatted_module_name already exists. Fetching remote branches..."
        cd "$clone_dir/$formatted_module_name" || exit
        module_name_path=$pwd
        git fetch --all

        # 检查新分支是否存在
        if git show-ref --verify --quiet "refs/remotes/origin/$branch_name"; then
            echo "Branch $branch_name found. Checking out..."
            git checkout -b "$branch_name" "origin/$branch_name" # 切换到远程分支
        else
            echo "Branch $branch_name not found."
        fi

        cd ../..
    else
        echo "Cloning $module_name from $GITLAB_URL$module_name into $clone_dir"
        git clone "$GITLAB_URL$module_name" "$clone_dir/$formatted_module_name"

        if [ $? -eq 0 ]; then
            cd "$clone_dir/$formatted_module_name" || exit
            echo "Fetching remote branches..."
            git fetch --all

            # 检查新分支是否存在
            if git show-ref --verify --quiet "refs/remotes/origin/$branch_name"; then
                echo "Branch $branch_name found. Checking out..."
                git checkout -b "$branch_name" "origin/$branch_name" # 切换到远程分支
            else
                echo "Branch $branch_name not found."
            fi

            cd ../..
        else
            echo "Failed to clone $module_name repository."
        fi
    fi
}

# 创建存放克隆代码的文件夹
CLONE_DIR="projects_clone"
mkdir -p "$CLONE_DIR"

# 克隆并切换到指定分支函数
stats_branch() {
    local module_name=${COMMON_NAME}-"$1.git" # 添加.git后缀
    local branch_name="${COMMON_NAME}-$2-$BRANCH_NAME_SUFFIX" # 生成分支名称
    local clone_dir="$3"

    local formatted_module_name=$(basename "$module_name" ".git") # 提取项目名称

    python2.7 gitstats.py $clone_dir/$formatted_module_name/ ./gitstats-output/$formatted_module_name

}
# 处理多个项目  
for project in "${PROJECTS[@]}"; do
    clone_and_checkout_branch "$project" "$project" "$CLONE_DIR"
done


# 处理多个项目，按人头统计各自代码提交量
for project in "${PROJECTS[@]}"; do
    cd $ROOT_PATH
    stats_branch "$project" "$project" "$CLONE_DIR"
done
